import os
import subprocess
import sys

# 检查是否提供了文件名参数
if len(sys.argv) < 2:
    print("Usage: {} filename".format(sys.argv[0]))
    sys.exit(1)

# 设置编译器路径
COMPILER = "C:/DEV/mingw64/bin/g++.exe"

# 检查文件名是否包含.cpp后缀，如果不包含，则添加
filename = sys.argv[1]
if not filename.endswith(".cpp"):
    filename += ".cpp"

# 检查文件是否存在
if not os.path.isfile(filename):
    print("File \"{}\" not found.".format(filename))
    sys.exit(1)

# 设置可执行文件名
executable = os.path.splitext(filename)[0] + ".exe"

# 编译文件
compile_command = [COMPILER, "-o", executable, filename]
result = subprocess.run(compile_command)
if result.returncode != 0:
    print("Compilation failed.")
    sys.exit(1)

# 运行生成的可执行文件，并重定向输入输出
with open('./test/in', 'r') as infile, open('./test/out', 'w') as outfile:
    run_command = [executable]
    result = subprocess.run(run_command, stdin=infile, stdout=outfile)
    if result.returncode != 0:
        print("Execution failed.")
        sys.exit(1)

# 删除生成的可执行文件
os.remove(executable)

print("Process completed.")